package com.study.mike.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.mike.common.exception.BizException;
import com.study.mike.mapper.SaleProductMapper;
import com.study.mike.model.entity.SaleProduct;
import com.study.mike.model.po.SaleProductPO;
import com.study.mike.model.po.ShelveSaleProductPO;
import com.study.mike.service.SaleProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author KangHui
 * @Date 2022/9/2 15:21
 */
@Service
public class SaleProductServiceImpl extends ServiceImpl<SaleProductMapper, SaleProduct> implements SaleProductService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addSaleProduct(SaleProductPO productPO) {
        // 新增商品信息
        return this.operationSaleProduct(productPO);
    }

    @Override
    public Boolean shelveSaleProduct(ShelveSaleProductPO po) {
        SaleProduct saleProduct = new SaleProduct();
        saleProduct.setId(po.getId());
        saleProduct.setStatus(po.getStatus());
        return this.updateById(saleProduct);
    }

    @Override
    public Boolean editSaleProduct(SaleProductPO productPO) {
        // 编辑商品信息
        return this.operationSaleProduct(productPO);
    }

    private Boolean operationSaleProduct(SaleProductPO productPO) {
        SaleProduct saleProduct = new SaleProduct();
        BeanUtils.copyProperties(productPO, saleProduct);
        try {
            this.saveOrUpdate(saleProduct);
        } catch (DuplicateKeyException e) {
            //手动回滚
            if (ObjectUtil.isNull(productPO.getId())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            throw new BizException("400", "商品编号重复");
        }
        return true;
    }
}
